package com.sunshine.lnuplusweb.controller;

import com.sunshine.lnuplusweb.callback.LoginCallback;
import com.sunshine.lnuplusweb.entities.Lesson;
import com.sunshine.lnuplusweb.entities.Schedule;
import com.sunshine.lnuplusweb.service.LessonService;
import com.sunshine.lnuplusweb.service.ScheduleService;
import com.sunshine.lnuplusweb.service.UserConfigService;
import com.sunshine.lnuplusweb.utils.ImportLessonByLNU;
import com.sunshine.lnuplusweb.utils.LoadSuperLesson;
import com.sunshine.lnuplusweb.utils.LoadSuperTerm;
import com.sunshine.lnuplusweb.utils.Result;
import com.sunshine.lnuplusweb.vo.superlesson.SuperBean;
import com.sunshine.lnuplusweb.vo.superlesson.SuperData;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 课程导入控制类
 */
@Controller
public class ImportLessonController {
    @Resource
    private ScheduleService scheduleService;

    @Resource
    private UserConfigService userConfigService;

    @Resource
    private LessonService lessonService;

    @GetMapping({"/import_lesson"})
    public String importLesson(Map<String, Object> map, HttpSession httpSession) {
        if (httpSession.getAttribute("userId") != null) {
            map.put("login", true);
            map.put("userId", "欢迎 " + httpSession.getAttribute("userId"));
        } else {
            map.put("login", false);
        }
        return "import_lesson";
    }

    //登录辽宁大学教务管理
    @PostMapping("/import_lesson_by_lnu")
    @ResponseBody
    public Result importLessonByLNU(
            Map<String, Object> map,
            HttpSession httpSession,
            @RequestParam("userId") String userId,
            @RequestParam("password") String password) {
        Result result = new Result();
        String loginUserId = (String) httpSession.getAttribute("userId");

        if (loginUserId == null) {
            //没有登录拒绝访问501
            result.setResultCode(Result.RESULT_SERVICE_REFUSED);
            result.setMessage("您还没有登录");
            return result;
        }
        //这个也不太可能，因为前端已经判断了
        else if (null == userId || null == password || userId.length() <= 0 || password.length() <= 0) {
            //400
            result.setResultCode(Result.RESULT_USER_ERROR);
            result.setMessage("输入的账号或密码为空");
            return result;
        }
        else {
            //获取登录的用户以获取该用户下是否有课表，获取到结果为-1则没有课表
            int nowScheduleId = userConfigService.getNowScheduleId(loginUserId);

            //判断是否有结果返回
            final boolean[] haveResult = {false};

            //用户不存在，其实不存在这种情况，但是怕恶意攻击
            if (-2 == nowScheduleId) {
                //501
                result.setResultCode(Result.RESULT_SERVICE_REFUSED);
                result.setMessage("您还没有登录");
                return result;
            }
            //用户下没有设置当前课程表
            else if (-1 == nowScheduleId) {
                //创建一个课表给该用户
                nowScheduleId = Math.abs((int) new Date().getTime());
                scheduleService.addSchedule(
                    new Schedule(
                        nowScheduleId,
                        userId,
                        "默认课表"
                    )
                );
                //更新到用户配置表中
                userConfigService.updateScheduleId(loginUserId, nowScheduleId);
            }

            //存在课表则执行解析课程
            ImportLessonByLNU importLessonByLNU = new ImportLessonByLNU(userId, password, nowScheduleId);
            int finalNowScheduleId = nowScheduleId;
            importLessonByLNU.load(new LoginCallback<List<Lesson>>() {
                @Override
                public void onSuccess(List<Lesson> lessonList) {
                    //先删除该课表ID中之前的课程
                    lessonService.deleteLessonByScheduleId(finalNowScheduleId);
                    //解析成功的课程放入课程的表中
                    lessonService.insertSchedule(lessonList);
                    result.setResultCode(Result.RESULT_OK);
                    haveResult[0] = true;
                }

                @Override
                public void onFail(String status) {
                    //获取课表错误并且返回一个错误信息400
                    result.setResultCode(Result.RESULT_USER_ERROR);
                    result.setMessage(status);
                    haveResult[0] = true;
                }
            });

            //用一个“死循环”来模拟异步请求回调
            while (!haveResult[0]) {
                System.out.println("loading...");
            }

            return result;
        }
    }

    private SuperData superData;

    //登录超级课程表
    @PostMapping("/login_by_super")
    @ResponseBody
    public Result<List<SuperBean>> loginBySuper(
            HttpSession httpSession,
            @RequestParam("userId") String userId,
            @RequestParam("password") String password) {
        Result<List<SuperBean>> result = new Result<>();
        String loginUserId = (String) httpSession.getAttribute("userId");

        if (loginUserId == null) {
            //没有登录拒绝访问501
            result.setResultCode(Result.RESULT_SERVICE_REFUSED);
            result.setMessage("您还没有登录");
            return result;
        }
        //这个也不太可能，因为前端已经判断了
        else if (null == userId || null == password || userId.length() <= 0 || password.length() <= 0) {
            //400
            result.setResultCode(Result.RESULT_USER_ERROR);
            result.setMessage("输入的账号或密码为空");
            return result;
        }
        else {
            //获取登录的用户以获取该用户下是否有课表，获取到结果为-1则没有课表
            int nowScheduleId = userConfigService.getNowScheduleId(loginUserId);

            //判断是否有结果返回
            final boolean[] haveResult = {false};

            //用户不存在，其实不存在这种情况，但是怕恶意攻击
            if (-2 == nowScheduleId) {
                //501
                result.setResultCode(Result.RESULT_SERVICE_REFUSED);
                result.setMessage("您还没有登录");
                return result;
            }

            //登录超级课程表获取学期
            LoadSuperTerm loadSuperTerm = new LoadSuperTerm();
            loadSuperTerm.login(userId, password, new LoginCallback<SuperData>() {
                @Override
                public void onSuccess(SuperData data) {
                    superData = data;
                    //登录成功，需要用户选择导入哪学期的课表
                    result.setResultCode(Result.RESULT_OK);
                    result.setMyData(superData.getSuperList());
                    haveResult[0] = true;
                }

                @Override
                public void onFail(String status) {
                    //登录超级课程表失败并且返回一个错误信息400
                    result.setResultCode(Result.RESULT_USER_ERROR);
                    result.setMessage(status);
                    haveResult[0] = true;
                }
            });

            //用一个“死循环”来模拟异步请求回调
            while (!haveResult[0]) {
                System.out.println("loading...");
            }

            return result;
        }
    }

    //登录超级课程表
    @PostMapping("/import_lesson_by_super")
    @ResponseBody
    public Result<List<SuperBean>> importLessonBySuper(
            HttpSession httpSession,
            @RequestParam("which") int which) {
        Result<List<SuperBean>> result = new Result<>();
        String loginUserId = (String) httpSession.getAttribute("userId");

        if (loginUserId == null) {
            //没有登录拒绝访问501
            result.setResultCode(Result.RESULT_SERVICE_REFUSED);
            result.setMessage("您还没有登录");
            return result;
        }
        else {
            //获取登录的用户以获取该用户下是否有课表，获取到结果为-1则没有课表
            int nowScheduleId = userConfigService.getNowScheduleId(loginUserId);

            //判断是否有结果返回
            final boolean[] haveResult = {false};

            //用户不存在，其实不存在这种情况，但是怕恶意攻击
            if (-2 == nowScheduleId) {
                //501
                result.setResultCode(Result.RESULT_SERVICE_REFUSED);
                result.setMessage("您还没有登录");
                return result;
            }
            //用户下没有设置当前课程表
            else if (-1 == nowScheduleId) {
                //创建一个课表给该用户
                nowScheduleId = Math.abs((int) new Date().getTime());
                scheduleService.addSchedule(
                        new Schedule(
                                nowScheduleId,
                                loginUserId,
                                "默认课表"
                        )
                );
                //更新到用户配置表中
                userConfigService.updateScheduleId(loginUserId, nowScheduleId);
            }

            //导入课程
            LoadSuperLesson loadSuperLesson = new LoadSuperLesson();
            int finalNowScheduleId = nowScheduleId;
            loadSuperLesson.load(which, nowScheduleId, superData, new LoginCallback<List<Lesson>>() {
                @Override
                public void onSuccess(List<Lesson> lessonList) {
                    //先删除该课表ID中之前的课程
                    lessonService.deleteLessonByScheduleId(finalNowScheduleId);
                    //解析成功的课程放入课程的表中
                    lessonService.insertSchedule(lessonList);
                    result.setResultCode(Result.RESULT_OK);
                    haveResult[0] = true;
                }

                @Override
                public void onFail(String status) {
                    //获取课表错误并且返回一个错误信息400
                    result.setResultCode(Result.RESULT_USER_ERROR);
                    result.setMessage(status);
                    haveResult[0] = true;
                }
            });

            //用一个“死循环”来模拟异步请求回调
            while (!haveResult[0]) {
                System.out.println("loading...");
            }

            return result;
        }
    }
}
